/**
 * 发票OCR列表
 */
import React  from 'react'
import { connect } from 'react-redux'
import { messages, queryCurrencyPrecision } from 'share/common'
import { Alert, Button, Modal, message } from 'antd'

import Invoice from 'containers/my-account/invoice'
import CreateInvoice from 'containers/my-account/create-invoice'
import Condition from 'components/condition'
const { If, Else } = Condition;

import expenseService from 'containers/my-account/expense.service'
import 'styles/my-account/components/invoice-ocr-list.scss'

class InvoiceOCRList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      receiptIsEdit: false,
      editReceipt: {},
      editReceiptIndex: 0,
      editReceiptAble: true, //编辑的发票是否可生成费用
      invoicesAble: [],
      invoicesDisable: [],
      saveSuccessList: [], //财务导入时，成功的数据
      saveFailedList: [], //财务导入时，失败的数据
    }
  }

  componentDidMount() {
    this.getInvoiceList()
  }

  componentWillReceiveProps() {
    this.getInvoiceList()
  }

  //信息是否完整（不需要补录）
  isCompleteInvoice = (resultCode) => {
    // 不完整code
    const resultCodes = ['R_2002', 'R_2007', 'R_2008', 'R_2009'];
    return !resultCodes.includes(resultCode);
  };

  //获取可生成费用／不可生成费用的发票列表
  getInvoiceList = () => {
    const { invoiceList } = this.props;
    let invoicesAble = [];
    let invoicesDisable = [];
    invoiceList.map(item => {
      let errorList = [];
      let PYTerrorList = []; // 票易通识别
      //信息缺失的标签提示需要前端处理显示，在所有标记的最前面
      if (item.isOk === 'N' && (!this.isCompleteInvoice(item.resultCode) || !item.invoiceInfo.type)) {
        errorList.push({
          title: messages('my-account.key288')/*信息缺失*/,
          level: "ERROR"
        })
      }
      // R_2015表示：票易通验签失败
      let indexR2015 = item.errorListV2 && item.errorListV2.findIndex(obj => obj.code === 'R_2015')
      if (item.isOk === 'N' && item.canCreateExpense === 'N' && indexR2015 > -1) {
        PYTerrorList.push({
          title: item.errorListV2 && item.errorListV2[indexR2015].title || undefined,
          message: item.errorListV2 && item.errorListV2[indexR2015].message || undefined,
        })
      }
      errorList.push(...(item.errorList || []));
      errorList.map((errorItem, errorIndex) => {
        errorList[errorIndex].name = errorItem.title;
        errorList[errorIndex].toast = errorItem.message;
      });
      item.invoiceInfo.receiptLabels = errorList;
      item.invoiceInfo.PYTerrorList = PYTerrorList;
      if (item.isOk === 'Y') {
        invoicesAble.push(item.invoiceInfo)
      } else {
        item.invoiceInfo.resultCode = item.resultCode;
        invoicesDisable.push(item.invoiceInfo)
      }
    });
    this.setState({ invoicesAble, invoicesDisable })
  };

  //渲染多发票显示列表
  renderInvoice = (invoiceList, isAble) => {
    let handleEdit = (receipt, index) => {
      this.setState({
        receiptIsEdit: true,
        editReceipt: receipt,
        editReceiptIndex: index,
        editReceiptAble: isAble
      })
    };
    let handleDelete = (receipt, index) => {
      let { invoicesAble, invoicesDisable } = this.state;
      if (isAble) {
        invoicesAble.splice(index, 1)
      } else {
        invoicesDisable.splice(index, 1)
      }
      this.setState({ invoicesAble, invoicesDisable });
      if (invoicesAble.length + invoicesDisable.length === 0) {
        this.props.cancelImport()
      }
    };
    return (
      <Invoice
        isOCRList
        invoiceList={invoiceList}
        handleEdit={handleEdit}
        handleDelete={handleDelete}
        createType={this.props.createType}
      />
    )
  };

  //编辑发票信息
  editInvoice = (receipt) => {
    let { editReceiptIndex, editReceiptAble, invoicesAble, invoicesDisable } = this.state;
    if (editReceiptAble) {
      invoicesAble[editReceiptIndex] = receipt
    } else {
      invoicesAble.push(receipt);
      invoicesDisable.splice(editReceiptIndex, 1)
    }
    this.setState({ receiptIsEdit: false }, () => {
      this.setState({ invoicesAble, invoicesDisable })
    })
  };

  //验证多发票逻辑
  validateMoreReceiptList = (invoiceInfo, invoiceIndex) => {
    const { receiptList, pageFrom } = this.props;
    const { invoicesAble } = this.state;
    let tip = '';
    let compareWithInvoice = (invoice) => {
      if (invoiceInfo.invoiceTypeNo === invoice.invoiceTypeNo) {
        //机票行程单单独验证号码、其他均需要代码号码均有值才验证
        if (String(invoiceInfo.invoiceTypeNo) === "150") {
          if (invoiceInfo.billingNo && invoiceInfo.billingNo === invoice.billingNo) {
            tip = messages('my-account.key263')/*存在重复发票*/;
          }
        } else if (
          invoiceInfo.billingCode && invoiceInfo.billingNo &&
          (invoiceInfo.billingCode === invoice.billingCode) &&
          (invoiceInfo.billingNo === invoice.billingNo)
        ) {
          tip = messages('my-account.key263')/*存在重复发票*/;
        }
      }

      if (invoice.vatInvoice || invoiceInfo.vatInvoice) { //有专票
        if (invoice.vatInvoice !== invoiceInfo.vatInvoice) { //发票类型不同
          tip = messages('my-account.key296')/*增值税专用发票与非增值税专用发票不能在一条费用行申请，请拆分费用行填写*/;
        }
        if (invoice.taxRate !== invoiceInfo.taxRate) { //税率不同
          if (pageFrom === undefined || pageFrom === 'myView') { //税率只需要在员工端校验 bug 33902
            tip = messages('my-account.key297')/*由于您上传的增值税专用发票的税率不同，请拆分费用行填写*/;
          }
        }
      }
    };
    receiptList.length > 0 && receiptList.some(item => {
      compareWithInvoice(item)
    });
    invoicesAble.map((item, index) => {
      if (index !== invoiceIndex) {
        compareWithInvoice(item)
      }
    });
    return tip;
  };

  //财务保存发票
  saveReceiptByFinance = (receipt) => {
    let { nowExpense } = this.props;
    let { saveSuccessList, saveFailedList } = this.state;
    receipt.invoiceOID = nowExpense.invoiceOID;
    expenseService.financialAuditInvoice(receipt).then(res => {
      if (res.data.code === '0000') {
        saveSuccessList.push(res.data.rows);
        this.setState({ saveSuccessList })
      } else {
        saveFailedList.push(receipt);
        this.setState({ saveFailedList })
      }
    }).catch(() => {
      saveFailedList.push(receipt);
      this.setState({ saveFailedList })
    });
  };

  onOk = () => {
    const { createType, receiptList } = this.props;
    let { invoicesAble } = this.state;
    let tip = '';
    invoicesAble.map((item, index) => {
      tip = this.validateMoreReceiptList(item, index)
    });
    if (tip) {
      Modal.info({
        title: tip
      })
    } else {
      console.log('111111', invoicesAble)
      if (invoicesAble[0].invoiceTypeNo === '08' && invoicesAble[0].originAttachment.fileType !== 'OFD') {
        message.warning('增值税电子专用发票，需上传OFD格式源文件')
        return
      }
     //, '10001' 医疗报销单 不控制 PDF / OFD
      if (['10', '20', '14'].includes(invoicesAble[0].invoiceTypeNo)) {
        if (!['OFD', 'PDF'].includes(invoicesAble[0].originAttachment.fileType)) {
          if (invoicesAble[0].invoiceTypeNo === '14') {
            message.warning('需要上传PDF或者OFD文件')
          } else {
            message.warning('电子发票，需要上传PDF或者OFD文件')
          }
          return
        }
      }
      console.log('invoicesAble', invoicesAble)
      if (createType === 2) { //财务操作
        this.setState({ loading: true });
        //单个费用最多关联50张发票
        if (receiptList.length + invoicesAble.length > 50) {
          let failedNum = receiptList.length + invoicesAble.length - 50;
          invoicesAble = invoicesAble.slice(0, 50 - receiptList.length);
          message.warning(messages('my-account.key322',{arg1: failedNum})/*单个费用最多关联50张发票，{arg1}张发票未关联成功*/);
        }
        //todo 待后端提供批量添加的api，暂时只能循环调用
        invoicesAble.map(receipt => {
          this.saveReceiptByFinance(receipt)
        });
        //获取保存发票的结果
        let getSaveResult = () => {
          const { saveSuccessList, saveFailedList } = this.state;
          if (saveSuccessList.length + saveFailedList.length === invoicesAble.length) {
            if (saveSuccessList.length === 0) {
              message.error(messages('my-account.key264',{arg1:saveFailedList.length})/*{arg1}张发票关联失败*/)
            } else if (saveFailedList.length === 0) {
              message.success(messages('my-account.key265',{arg1:saveSuccessList.length})/*{arg1}张发票关联成功*/)
            } else {
              message.warning(messages('my-account.key266',{arg1:saveFailedList.length,arg2:saveSuccessList.length})/*{arg1}张发票关联失败，{arg2}张发票关联成功*/)
            }
            this.setState({ loading: false, saveSuccessList: [], saveFailedList: [] });
            this.props.handleImport(saveSuccessList);
            return
          }
          setTimeout(() => {
            getSaveResult()
          }, 1000);
        };
        getSaveResult();
      } else {
        //单个费用最多关联50张发票
        if (receiptList.length + invoicesAble.length > 50) {
          let failedNum = receiptList.length + invoicesAble.length - 50;
          invoicesAble = invoicesAble.slice(0, 50 - receiptList.length);
          message.warning(messages('my-account.key322',{arg1: failedNum})/*单个费用最多关联50张发票，{arg1}张发票未关联成功*/);
        }
        this.props.handleImport(invoicesAble)
      }
    }
  };

  render() {
    const { invoiceUserFp, expenseReport, currencyList, nowExpense, receiptList } = this.props;
    const { loading, receiptIsEdit, editReceipt, invoicesAble, invoicesDisable } = this.state;
    //若未识别到币种或币种未启用，则置空
    let currency = undefined;
    if (currencyList && currencyList.some(item => item.currency === editReceipt.vatInvoiceCurrencyCode)) {
      currency = editReceipt.vatInvoiceCurrencyCode;
    }
    return (
      <div className="invoice-ocr-list">
        <Condition>
          <If value={receiptIsEdit}>
            <CreateInvoice
              receipt={editReceipt}
              invoiceUserFp={invoiceUserFp}
              userOID={expenseReport ? expenseReport.applicantOID : ''}
              currencyList={currencyList}
              invoiceOID={nowExpense.invoiceOID}
              receiptOperateScene={2} //费用新增发票
              receiptList={receiptList}
              currency={currency}
              pageFrom="OCR"
              onCreate={this.editInvoice}
              onBack={() => this.setState({ receiptIsEdit: false })}
            />
          </If>
          <Else>
            <Alert
              message={messages('my-account.key267',{arg1:invoicesAble.length + invoicesDisable.length})/*共识别{arg1}张发票，点击可 核对/修改 发票信息*/}
              type="info"
              showIcon
            />

            <If value={invoicesAble.length}>
              <div className="check-success-tip">{messages('my-account.key268',{arg1:invoicesAble.length})/*以下{arg1}张发票可生成费用*/}</div>
              {this.renderInvoice(invoicesAble, true)}
            </If>

            <If value={invoicesDisable.length}>
              <div className="check-error-tip">{messages('my-account.key269',{arg1:invoicesDisable.length})/*以下{arg1}张发票不可生成费用*/}</div>
              {this.renderInvoice(invoicesDisable, false)}
            </If>

            <div className="slide-footer">
              <Button onClick={this.props.cancelImport}>{messages('common.cancel')/*取消*/}</Button>
              <Button
                type="primary"
                disabled={!invoicesAble.length}
                onClick={this.onOk}
                loading={loading}
              >{messages('common.ok')/*确定*/}</Button>
            </div>
          </Else>
        </Condition>
      </div>
    )
  }
}

InvoiceOCRList.propTypes = {
  invoiceList: React.PropTypes.array,
  invoiceUserFp: React.PropTypes.object, //申请人费用FP
  currencyList: React.PropTypes.array, //费用币种list
  expenseReport: React.PropTypes.object,
  nowExpense: React.PropTypes.object,
  receiptList: React.PropTypes.array,
  createType: React.PropTypes.number, //1.用户操作类型 2.财务操作类型
  pageFrom: React.PropTypes.string,
  handleImport: React.PropTypes.func,
  cancelImport: React.PropTypes.func,
};

function mapStateToProps() {
  return { }
}

export default connect(mapStateToProps)(InvoiceOCRList);
